package com.ruoyi.modules.appController;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.Result;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.modules.admin.service.ISysConfigService;
import com.ruoyi.modules.domain.DyAppUser;
import com.ruoyi.modules.domain.vo.DyAppUserDTO;
import com.ruoyi.modules.domain.vo.MoneyRecordDto;
import com.ruoyi.modules.service.IDyAppUserService;
import com.ruoyi.modules.service.INumRecordService;
import com.ruoyi.modules.util.DouyinRequestUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutionException;

/**
 * 抖音app用户Controller
 *
 * @author ruoyi
 * @date 2022-01-22
 */
@Api(tags = "app - 抖音app用户")
@RestController
@RequestMapping("/app/dyAppUser")
@Slf4j
public class AppDyAppUserController extends BaseController {
    @Autowired
    private IDyAppUserService dyAppUserService;
    @Autowired
    ISysConfigService iSysConfigService;
    @Autowired
    INumRecordService numRecordService;

    @Autowired
    private TokenService tokenService;

    @ApiOperation(value="抖音用户授权", notes="抖音用户授权")
    @GetMapping(value = "/openApi/authorization/{agentUserId}")
    @ApiImplicitParams({
    })
    public void getAgentUserInfo(@PathVariable("agentUserId") Long agentUserId, String code, HttpServletResponse response) throws IOException {


        log.info("抖音用户授权  agentUserId: {} , code : {}", agentUserId, code);


        JSONObject login_jsonObject = DouyinRequestUtil.loginByCode(code);
        log.info("授权结果 ： " + login_jsonObject);

        String open_id = login_jsonObject.getString("open_id");
        String access_token = login_jsonObject.getString("access_token");

        if (StringUtils.isEmpty(open_id)){
            log.info("授权失败!");
            return ;
        }


        DyAppUser dyAppUser = dyAppUserService.getOne(new LambdaQueryWrapper<DyAppUser>()
                .eq(DyAppUser::getAgentUserId, agentUserId)
                .eq(DyAppUser::getOpenId, open_id)
                .last("limit 1")
        );

        if (dyAppUser == null){
            log.info("第一次授权");
            dyAppUser = new DyAppUser();
            dyAppUser.setAgentUserId(agentUserId);
            dyAppUser.setOpenId(open_id);
            dyAppUser.setCode(generateCode());
        }
        dyAppUser.setAccessToken(access_token);


        JSONObject userInfo_jsonObject = DouyinRequestUtil.getUserInfo(open_id, access_token);

        dyAppUser.setNickName(userInfo_jsonObject.getString("nickname"));
        dyAppUser.setAvatar(userInfo_jsonObject.getString("avatar"));
        dyAppUser.setSex(userInfo_jsonObject.getString("gender"));
        dyAppUser.setCountry(userInfo_jsonObject.getString("country"));
        dyAppUser.setProvince(userInfo_jsonObject.getString("province"));
        dyAppUser.setCity(userInfo_jsonObject.getString("city"));
        dyAppUser.setEAccountRole(userInfo_jsonObject.getString("e_account_role"));
        dyAppUser.setPhone(userInfo_jsonObject.getString("phone"));

        dyAppUser.setCreateTime(new Date());
        dyAppUser.setUpdateTime(null);
        dyAppUserService.saveOrUpdate(dyAppUser);

        log.info("授权成功!");
        response.sendRedirect("https://duoduodan1688.cn/loginSuccess.html?code="+dyAppUser.getCode());
    }





    /**
     * 查询抖音app用户列表
     */
    @ApiOperation(value="抖音app用户列表根据代理用户id", notes="抖音app用户列表根据代理用户id")
    @GetMapping("/listByAgentUserId")
    public TableDataInfo listByAgentUserId(HttpServletRequest req, DyAppUser dyAppUser) {

        Long agentUserId = tokenService.getUserId(req);

        startPage();
        List<DyAppUser> list = dyAppUserService.listDyAppUser(agentUserId, dyAppUser.getNickName(), dyAppUser.getCode());
        return getDataTable(list);
    }


    /**
     * app用户详情
     */
    @ApiOperation(value="app用户详情", notes="app用户详情")
    @GetMapping("/getAppUserDetail")
    public Result getAppUserDetail(HttpServletRequest req, Long appUserId) {

//        Long agentUserId = tokenService.getUserId(req);

        DyAppUser dyAppUser = dyAppUserService.getById(appUserId);
        return Result.ok(dyAppUser);
    }
    /**
     * 修改账号标签
     */
    @ApiOperation(value="修改账号标签", notes="修改账号标签")
    @GetMapping("/editAccountLabel")
    public Result editAccountLabel(HttpServletRequest req, Long appUserId, String label) {

        dyAppUserService.update(new LambdaUpdateWrapper<DyAppUser>()
                .set(DyAppUser::getLabel, label)
                .eq(DyAppUser::getId, appUserId));
        return Result.ok();
    }

    /**
     * 数据分析 付费
     */
    @ApiOperation(value="数据分析 付费", notes="数据分析 付费")
    @GetMapping("/dataAnalysis")
    @Transactional
    public Result dataAnalysis(HttpServletRequest req, Long appUserId) {

        Long agentUserId = tokenService.getUserId(req);


        DyAppUser dyAppUser = dyAppUserService.getById(appUserId);

        MoneyRecordDto moneyRecordDto = numRecordService.useNumAndGetId(agentUserId, dyAppUser);
        if (!moneyRecordDto.isSuccess()){
            return Result.error("查询次数不足!");
        }

        DyAppUserDTO dyAppUserDTO = new DyAppUserDTO();
        BeanUtils.copyProperties(dyAppUser, dyAppUserDTO);

        //支付凭证
        String voucher = ""+moneyRecordDto.getMoneyRecordId();
        dyAppUserService.setDyAppUserDTo(voucher, dyAppUserDTO);


        //修改看过状态
        dyAppUser.setSeeTime(new Date());
        dyAppUserService.updateById(dyAppUser);

        Result<Object> ok = Result.ok();
        ok.setResult(voucher);
        return ok;
    }





    /**
     * 数据概括  大部分数据
     */
    @ApiOperation(value="数据概括  大部分数据", notes="数据概括  大部分数据")
    @GetMapping("/generalizeData")
    public Result generalizeData(HttpServletRequest req, String voucher) throws ExecutionException, InterruptedException {

//        Long agentUserId = tokenService.getUserId(req);
        return Result.ok(dyAppUserService.generalizeData(voucher));
    }


    /**
     * 粉丝基本数据
     */
    @ApiOperation(value="粉丝基本数据", notes="粉丝基本数据")
    @GetMapping("/fansData")
    public Result fansData(HttpServletRequest req, String voucher) {

//        Long agentUserId = tokenService.getUserId(req);
        DyAppUserDTO dyAppUserDTO = dyAppUserService.getDyAppUserDTo(voucher);
        return Result.ok(DouyinRequestUtil.fansData(dyAppUserDTO.getOpenId(), dyAppUserDTO.getAccessToken()));
    }





    /**
     * 视频列表
     */
    @ApiOperation(value="视频列表", notes="视频列表")
    @GetMapping("/listVideoByAppUserId")
    public Result listVideoByAppUserId(HttpServletRequest req, String voucher, Long cursor) {

        //        Long agentUserId = tokenService.getUserId(req);
        DyAppUserDTO dyAppUserDTO = dyAppUserService.getDyAppUserDTo(voucher);
        return Result.ok(dyAppUserService.videoList(voucher, dyAppUserDTO, cursor));

    }



//    /**
//     * 视频播放分析
//     */
//    @ApiOperation(value="视频播放分析", notes="视频播放分析")
//    @GetMapping("/videoPlayData")
//    public Result videoPlayData(HttpServletRequest req, String voucher) {
//
////        Long agentUserId = tokenService.getUserId(req);
//        DyAppUserDTO dyAppUserDTO = dyAppUserService.getDyAppUserDTo(voucher);
//        return Result.ok(DouyinRequestUtil.videoPlayData(dyAppUserDTO.getOpenId(), dyAppUserDTO.getAccessToken()));
//    }


    // 随机生成六位不重复的数字
    private static String generateCode() {
        String chars = "0123456789";
        String res = "";
        for (int i = 0; i < 6; i++) {
            Random rd = new Random();
            res += chars.charAt(rd.nextInt(chars.length() - 1));
        }
        return res;
    }
}
